Increasing triplet subsequence¶
Time: O(N); Space: O(1); medium
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should: * Return true if there exists i, j, k such that arr[i] < arr[j] < arr[k] given 0 <= i < j < k <= n-1 else return false.
Your algorithm should run in O(N) time complexity and O(1) space complexity.
Example 1:
Input: nums = [1, 2, 3, 4, 5]
Output: True
Example 2:
Input: nums = [5, 4, 3, 2, 1]
Output: False
[1]:
class Solution1(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
min_num, a, b = float("inf"), float("inf"), float("inf")
for c in nums:
if min_num >= c:
min_num = c
elif b >= c:
a, b = min_num, c
else: # a < b < c
return True
return False
[2]:
s = Solution1()
nums = [1, 2, 3, 4, 5]
assert s.increasingTriplet(nums) == True
nums = [5, 4, 3, 2, 1]
assert s.increasingTriplet(nums) == False
[5]:
import bisect
class Solution_Generalization(object):
"""
Time: O(N * logk); Space: O(k)
Generalization of k-uplet.
"""
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def increasingKUplet(nums, k):
inc = [float('inf')] * (k - 1)
for num in nums:
i = bisect.bisect_left(inc, num)
if i >= k - 1:
return True
inc[i] = num
return k == 0
return increasingKUplet(nums, 3)
[6]:
s = Solution_Generalization()
nums = [1, 2, 3, 4, 5]
assert s.increasingTriplet(nums) == True
nums = [5, 4, 3, 2, 1]
assert s.increasingTriplet(nums) == False